<template>
  <div class="default-menu">
    <div class="panel-header">
      <h4>图层控制</h4>
      <el-button type="text" @click="closeHandler" class="close-btn">×</el-button>
    </div>
    <div v-for="layer in layers" :key="layer.id" class="layer-item">
      <div class="layer-info">
        <input type="checkbox" v-model="layer.visible" @change="updateLayerVisibility(layer)">
        <span class="layer-name">{{ layer.name }}</span>
      </div>
      <el-button type="text" @click="openLayerSettings(layer)" icon="el-icon-setting"
        class="layer-settings-btn"></el-button>

      <!-- 图层设置弹窗 -->
      <div class="custom-dialog-mask" v-if="showLayerSettings" @click.self="showLayerSettings = false">
        <div class="custom-dialog">
          <div class="dialog-header">
            <h3>{{ currentEditLayer?.name }} 样式设置</h3>
            <button class="close-btn" @click="showLayerSettings = false">&times;</button>
          </div>

          <div class="dialog-body">
            <div class="form-group">
              <label>透明度</label>
              <input type="range" v-model="currentEditLayer.style.opacity" min="0" max="1" step="0.1"
                @input="updateLayerOpacity">
              <span class="value-display">{{ currentEditLayer.style.opacity }}</span>
            </div>

            <div class="form-group">
              <label>显示层级</label>
              <input type="number" v-model="currentEditLayer.style.zIndex" min="0" max="100" @change="updateLayerZIndex">
            </div>

            <div class="form-group">
              <label>填充颜色</label>
              <input type="color" v-model="currentEditLayer.style.fill" @change="updateLayerStyle">
            </div>

            <div class="form-group">
              <label>边框颜色</label>
              <input type="color" v-model="currentEditLayer.style.stroke" @change="updateLayerStyle">
            </div>

            <div class="form-group">
              <label>边框宽度</label>
              <input type="number" v-model.number="currentEditLayer.style.width" min="1" max="10"
                @change="updateLayerStyle">
            </div>

            <div class="form-group">
              <label>预设样式</label>
              <select v-model="selectedPreset" @change="applyPresetStyle">
                <option v-for="preset in presetStyles" :key="preset.name" :value="preset">
                  {{ preset.name }}
                </option>
              </select>
            </div>
          </div>

          <div class="dialog-footer">
            <button class="confirm-btn" @click="completeLayerSettings">完成</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator';
import { LayerConfig } from '@/types/map';
import { getGeoJsonLayer} from '@/utils/amap-helper';
import { Getter } from 'vuex-class';
declare const AMap: any;
@Component
export default class LayerControl extends Vue {
  @Prop({ default: () => [] }) layers!: LayerConfig[];
  @Prop({ default: () => [] }) presetStyles!: any[];
  @Prop() map;
  @Getter vectorInfo?:any;
  @Getter objectInfo?:any;

  

  private showLayerSettings = false;
  private currentEditLayer: LayerConfig | null = null;
  private selectedPreset: any = '';

  private updateLayerVisibility(layerInfo: any) {
     if(layerInfo.visible ){
            this.map.add(layerInfo.layer);
        }else{
            this.map.remove(layerInfo.layer);
        }
     this.$emit('update-layer-visibility', layerInfo);
  }

  private openLayerSettings(layer: LayerConfig) {
    this.currentEditLayer = { ...layer };
    this.showLayerSettings = true;
  }

  private updateLayerOpacity(value: number) {
    if (!this.currentEditLayer) return;
  }

  private completeLayerSettings() {
    this.showLayerSettings = false;
    if(!this.currentEditLayer) return;

    this.addVectorLayer(this.currentEditLayer.name,undefined,this.vectorInfo)
        // 触发视图更新
   
    this.$emit('update-layer-settings', );
    this.$forceUpdate();
  } 

  private updateLayerZIndex(value: number) {
    if (!this.currentEditLayer) return;

    this.ayncLayerInfo();
  }

  private updateLayerStyle() {
    if (!this.currentEditLayer) return;
    this.ayncLayerInfo();
  }

  private ayncLayerInfo() {
    if (!this.currentEditLayer) return;
    const index = this.layers.findIndex(l => l.id === this.currentEditLayer?.id);
    if (index > -1) {
      this.layers.splice(index, 1, this.currentEditLayer);
    }
  }

  private applyPresetStyle() {
    if (!this.currentEditLayer) {
      this.$message.warning("请先选择要设置的图层");
      return;
    }

    this.currentEditLayer.style = {
      ...this.currentEditLayer.style,
      fill: this.selectedPreset.fill,
      stroke: this.selectedPreset.stroke,
      width: this.selectedPreset.width
    };

    this.updateLayerStyle();
    this.$message.success(`已应用 ${this.selectedPreset.name} 样式`);
    this.$forceUpdate();
  }

   addVectorLayer(layerName: string, layerType?: string,geoData?: any, style?:any) {
        if (!this.map) return;
        const existingLayerIndex = this.layers.findIndex(l => l.name === layerName);
        if(layerType){
            const matchedStyle = this.presetStyles.find(s => s.type === layerType);
            style = matchedStyle;
        }
  
      
        if(existingLayerIndex > -1){
             const existingLayer = this.layers[existingLayerIndex];
             if(!style){
                style = existingLayer.style;
             }
             this.map.remove(existingLayer.layer);
        
             const newLayer = getGeoJsonLayer(geoData,style);
             existingLayer.layer = newLayer;
             existingLayer.style = style;
             this.map.add(newLayer);
             this.map.f
             this.$message.success('图层更新成功');
        }else{
             if(!style){
            style = this.presetStyles[0];
        }
            const newLayer = getGeoJsonLayer(geoData,style);
            this.map.add(newLayer);
            this.layers.push({
                id: `vector-${Date.now()}`,
                name: layerName,
                type: layerType || 'default',
                layer: newLayer,
                visible: true,
                style: style
            });
            this.$message.success('图层添加成功');
        }
    }

  closeHandler(){
    this.$emit('close-layer-settings');
  }

  mounted(){

     this.addVectorLayer("行政区划",'default',this.vectorInfo);
    this.fitToLayerBounds(this.vectorInfo);
  }

  // 新增方法：调整地图视图到图层范围（高德地图实现）
private fitToLayerBounds(geoData: any) {
    if (!this.map || !geoData) return;
    
    try {
        // 计算图层的地理边界
        let minLng = 180, maxLng = -180, minLat = 90, maxLat = -90;
        
        // 递归遍历所有坐标点
        const traverseCoordinates = (coords: any) => {
            if (Array.isArray(coords[0])) {
                coords.forEach(coord => traverseCoordinates(coord));
            } else {
                const [lng, lat] = coords;
                minLng = Math.min(minLng, lng);
                maxLng = Math.max(maxLng, lng);
                minLat = Math.min(minLat, lat);
                maxLat = Math.max(maxLat, lat);
            }
        };
        
        // 处理GeoJSON数据
        geoData.features.forEach((feature: any) => {
            const coordinates = feature.geometry.coordinates;
            traverseCoordinates(coordinates);
        });
        
        // 创建边界对象
        const bounds = new AMap.Bounds(
            new AMap.LngLat(minLng, minLat),
            new AMap.LngLat(maxLng, maxLat)
        );
        
        // 调整地图视图
        this.map.setBounds(bounds, true, [50, 50, 50, 50]); // 四周留白50像素
    } catch (error) {
        console.error('调整图层范围失败:', error);
    }
}
}
</script>

<style scoped>
/* 保留原有样式或根据需要调整 */
.custom-dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.custom-dialog {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  width: 400px;
  max-width: 90vw;
  animation: dialogSlideIn 0.3s ease;
}

.dialog-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}

.dialog-header h3 {
  margin: 0;
  font-size: 14px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  line-height: 1;
  padding: 0 4px;
}

.close-btn:hover {
  color: #333;
}

.dialog-body {
  padding: 16px;
}

.form-group {
  margin-bottom: 1rem;
  display: flex;
  align-items: center;
  gap: 12px;
}

.form-group label {
  flex: 0 0 80px;
  font-size: 12px;
  color: #666;
}



input[type="range"] {
  flex: 1;
  height: 4px;
  background: #ddd;
  border-radius: 2px;
  -webkit-appearance: none;
}

input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 16px;
  height: 16px;
  background: #1890ff;
  border-radius: 50%;
  cursor: pointer;
}

input[type="number"] {
  width: 80px;
  padding: 6px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

input[type="color"] {
  width: 40px;
  height: 32px;
  padding: 2px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

select {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  background: white;
}

.value-display {
  width: 40px;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.dialog-footer {
  padding: 16px;
  border-top: 1px solid #eee;
  text-align: right;
}

.confirm-btn {
  background: #1890ff;
  color: white;
  border: none;
  padding: 8px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.confirm-btn:hover {
  background: #40a9ff;
}

/* 图层项样式 */
.layer-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 8px 0;
    border-bottom: 1px solid #eee;
}


.layer-settings-btn {
    padding: 5px;
    margin-left: 10px;
}

@keyframes dialogSlideIn {
  from {
    transform: translateY(-20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.panel-header {
  
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #f8f9fa;
}

.close-btn {
    font-size: 20px;
    color: #999;

    &:hover {
        color: #666;
    }
}
</style>